import {
	getMenuList
} from "@/network/sys/menu";
import router from '@/router/index'
import Index from '@/views/index'
import Home from '@/views/Home.vue';

const DRouter = {
	state: {
		userRoutes: [], //用户后台
		sidebarRouters: [], //菜单路由
		sidebarMenuList: [] //菜单列表
	},

	mutations: {
		SET_USER_ROUTES: (state, routes) => {
			state.userRoutes = routes
		},
		SET_SIDEBAR_ROUTERS: (state, routers) => {
			state.sidebarRouters = routers
		},
		SET_SIDEBAR_MENU_LIST: (state, data) => {
			state.sidebarMenuList = data
		}
	},
	actions: {
		// 生成路由
		GenerateRoutes({
			commit
		}) {
			return new Promise(resolve => {
				getMenuList().then((res) => {
					if (res.code !== 0) {
						console.log(res.msg)
						return;
					}
					
					const sidebarRoutes = filterRouter(res.data)
					const newRoutes = createNewRoutes(res.data)
					//  sidebarMenuList = res.data;R
					commit('SET_SIDEBAR_MENU_LIST', res.data)
					commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
					commit('SET_USER_ROUTES', newRoutes)


					//添加动态路由
					for (let i = 0; i < newRoutes.length; i++) {
						router.addRoute(newRoutes[i])
					}

					resolve(res.data)
				}).catch(function(err) {
					console.log(err);
				})

			})
		}
	}
}

//使用二级菜单
function createNewRoutes(menuListData) {
	let routes = [];

	for (let i = 0; i < menuListData.length; i++) {
		let menuList = menuListData[i];
		let menuListChildren = menuList.children;
		for (let j = 0; j < menuListChildren.length; j++) {
			let menu = menuListChildren[j];
			//解析path
			let pathStrs = menu.url.split('/').filter((str) => {
				if (str.length > 0) {
					return true
				}
			})
			if (pathStrs.length >= 2) {
				let route = {
					path: '',
					name: '',
					component: '',
					children: ''
				}
				route.path = pathStrs[1];
				route.name = menu.id;
				let name1 = route.name.toString();
				if (menu.component) {
					
					route.component = loadView(menu.component);
				} else {
					route.component = Index;
				}
				let bool = false;
				for (let k = 0; k < routes.length; k++) {
					let rout = routes[k];
					if (rout.name == (pathStrs[0])) {
						bool = true
						rout.children.push(route);
					}
				}
				if (!bool) {
					//添加父节点
					routes = routes.concat([{
						path: '/' + pathStrs[0],
						name: pathStrs[0],
						component: Index,
						children: new Array(route)
					}])
				}
			}
		}
	}
	return routes
}

function filterRouter(menuListData) {
	let routes = new Array()

	for (let menu of menuListData) {
		let route = {
			path: '',
			name: '',
			component: '',
			children: '',
			meta: {
				icon: '',
				name: ''
			}
		}
		route.path = menu.url == null ? "" : menu.url.length == 0 ? menu.url : menu.url.indexOf('/') == 0 ? menu.url :
			'/' + menu.url;
		route.name = menu.id;
		route.meta.icon = menu.icon;
		route.meta.name = menu.name;
		if (menu.component) {
			route.component = loadView(menu.component);
		} else {
			route.component = Index;
		}

		if (menu.children != null && menu.children && menu.children.length) {
			route.children = filterRouter(menu.children)
		}

		if (Array.isArray(routes))
			routes = routes.concat(route)
		else
			routes = filterRouter(menu.children)

	}
	return routes
}


// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
	return asyncRouterMap.filter(route => {
		if (type && route.children) {
			route.children = filterChildren(route.children)
		}
		if (route.component) {
			// Layout ParentView 组件特殊处理
			if (route.component === 'Index') {
				route.component = Index
			} else if (route.component === 'ParentView') {
				route.component = ParentView
			} else {
				route.component = loadView(route.component)
			}
		}
		if (route.children != null && route.children && route.children.length) {
			route.children = filterAsyncRouter(route.children, route, type)
		} else {
			delete route['children']
			delete route['redirect']
		}
		return true
	})
}

function filterChildren(childrenMap, lastRouter = false) {
	let children = []
	childrenMap.forEach((el, index) => {
		if (el.children && el.children.length) {
			if (el.component === 'ParentView') {
				el.children.forEach(c => {
					c.path = el.path + '/' + c.path
					if (c.children && c.children.length) {
						children = children.concat(filterChildren(c.children, c))
						return
					}
					children.push(c)
				})
				return
			}
		}
		if (lastRouter) {
			el.path = lastRouter.path + '/' + el.path
		}
		children = children.concat(el)
	})
	return children
}

export const loadView = (view) => { // 路由懒加载
	if (view.indexOf('/') == 0) {
		return () => Promise.resolve(require(`@/views${view}`).default)
	} else
		return () => Promise.resolve(require(`@/views/${view}`).default)
}

export default DRouter
